import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class BannerService {

  constructor( public http: Http) { }

  // 获取数据
  getData(params): Observable<any> {
    return this.http.get(ROOT_URL + 'Banner/index', {params})
        .map(this.extractData)
        .catch(this.handleError);
  }
  // 上架下架
    setState(params): Observable<any> {
        return this.http.put(ROOT_URL + 'Banner/shelves', params)
            .map(this.extractData)
            .catch(this.handleError);
    }

    // 新增轮播图
    addBanner(params): Observable<any> {
        return this.http.post(ROOT_URL + 'Banner/save', params)
            .map(this.extractData)
            .catch(this.handleError);
    }

    // 删除轮播图
    bannerDelete(params): Observable<any> {
        return this.http.delete(ROOT_URL + 'Banner/delete', {params})
            .map(this.extractData)
            .catch(this.handleError);
    }

  private extractData(res: Response) {
    const body = res.json();
    if (body['code'] === 5003) {
      alert('账号在其他设备登录');
      localStorage.token = '';
      localStorage.tokenTime = '';
      window.location.reload();
    }
    return body;
  }
  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
